<?php

namespace Modules\Order\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Order\Entities\BaseOrder as Order;

use Validator;
use ThrowException;
use Auth;
use QrCode;

class OrderOfflineController extends Controller
{
    // 用户端获取订单核销码信息
    public function verifyInfo(Request $req, $uuid)
    {
        $user = Auth::requireLoginUser();

        $order = $user->orders()->where('uuid', $uuid)->first() ?: ThrowException::Conflict('找不到此订单');

        $code = $order->code;

        $info = [
            'code' => $code,
            'qrcode' => base64_encode(QrCode::format('png')->margin(0)->size(400)->generate($code))
        ];

        return [
            'info' => $info
        ];
    }

    // 管理端扫码
    public function scan(Request $req)
    {
        $rule = [
            'code' => ['required']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $code = $req->code;
        $order = Order::where('code', $code)->with(['skus', 'address'])->first() ?: ThrowException::Conflict('找不到此订单');

        return [
            'info' => $order
        ];
    }

    // 管理端确认扫码
    public function scanConfirm(Request $req)
    {
        $rule = [
            'code' => ['required']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $code = $req->code;
        $order = Order::where('code', $code)->with(['skus', 'address'])->first() ?: ThrowException::Conflict('找不到此订单');

        // 线下核销
        $order->offlineUse();

        return [];
    }
}
